<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import io from 'socket.io-client'
import { useUserStore } from '@/stores/user'
// TODO初始化的时候，要加query参数，用于区分用户，以及携带token
// 创建socket连接
const userStore = useUserStore()
const socket = ref(null)
const chatList = ref([])
function initSocket() {
  socket.value = io('http://localhost:3000', {
    auth: {
      token: userStore.token
    }
  })
  socket.value.on('connect', () => {
    console.log('socket连接成功')
  })
  socket.value.on('disconnect', () => {
    console.log('socket断开连接')
  })
  socket.value.on('error', (error) => {
    console.error('Socket错误:', error.message)
  })
  socket.value.on('joinedRoom', (data) => {
    console.log('成功加入房间:', data.room)
  })
  socket.value.on('userJoined', (data) => {
    console.log('新用户加入房间:', data)
  })
  socket.value.on('userLeft', (data) => {
    console.log('用户离开房间:', data)
  })
  socket.value.on('receiveMessage', (data) => {
    console.log(data)
    // console.log(socket.value.id)
    chatList.value.push(data)
    console.log(chatList.value)
  })
  // 加入房间
  socket.value.emit('joinRoom', 'room1')
}

const chatValue = ref('')
function sendMessage() {
  socket.value.emit('sendMessage', {
    from: userStore.userInfo.id,
    to: 'enetrpriseId',
    room: 'room1',
    message: chatValue.value,
    timestamp: new Date()
  })
  chatValue.value = ''
}

onMounted(() => {
  initSocket()
})
onUnmounted(() => {
  // 离开页面，断开连接
  socket.value.disconnect()
  // 离开房间
  socket.value.emit('leaveRoom', 'room1')
})
</script>

<template>
  <div class="chat-wrapper">
    <div class="chat-content">
      <div v-for="item in chatList" :key="item.id" class="message-container">
        <div :class="['message-box', item.from === userStore.userInfo.id ? 'sent' : 'received']">
          <div class="message-content">
            {{ item.message }}
          </div>
          <div class="message-time">
            {{ new Date(item.timestamp).toLocaleTimeString() }}
          </div>
        </div>
      </div>
    </div>
    <div class="chat-input-container">
      <div class="input-wrapper">
        <el-input
          v-model="chatValue"
          class="message-input"
          placeholder="请输入消息..."
          :maxlength="500"
          @keyup.enter="sendMessage"
        />
        <el-button
          type="primary"
          class="send-button"
          :disabled="!chatValue.trim()"
          @click="sendMessage"
        >
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chat-wrapper {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;

  .chat-content {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    margin-bottom: 80px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .message-container {
      margin: 16px 0;
      &::after {
        content: '';
        display: table;
        clear: both;
      }
    }

    .message-box {
      max-width: 70%;
      display: block;

      &.sent {
        float: right;
        .message-content {
          background-color: #409eff;
          color: white;
          border-radius: 12px 2px 12px 12px;
        }
        .message-time {
          text-align: right;
        }
      }

      &.received {
        float: left;
        .message-content {
          background-color: #e9ecef;
          color: #333;
          border-radius: 2px 12px 12px 12px;
        }
      }

      .message-content {
        padding: 12px 16px;
        word-wrap: break-word;
        font-size: 14px;
        line-height: 1.4;
      }

      .message-time {
        font-size: 12px;
        color: #909399;
        margin-top: 4px;
      }
    }

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #c0c4cc;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: #f5f7fa;
    }
  }

  .chat-input-container {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20px;
    background: white;
    box-shadow: 0 -2px 12px 0 rgba(0, 0, 0, 0.1);

    .input-wrapper {
      display: flex;
      align-items: center;
      max-width: 1200px;
      margin: 0 auto;
      gap: 16px;

      .message-input {
        flex: 1;

        :deep(.el-input__inner) {
          border-radius: 20px;
          padding: 0 20px;
        }
      }

      .send-button {
        border-radius: 20px;
        padding: 0 24px;
      }
    }
  }
}
</style>
